package cn.edu.tju.cas.util;

import cn.edu.tju.cas.entity.UserEntity;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.sql.Time;
import java.sql.Timestamp;

/**
 * Created by catold on 16/4/7.
 */
public class XmlDealer {
     public static DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

    public static void main(String[] args) {
        UserEntity userEntity = getFromXml("<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>    <cas:authenticationSuccess>        <cas:user>1</cas:user>        <cas:attributes>                                                <cas:CREDIT>1        </cas:CREDIT>                                    <cas:UPDATETIME>2016-04-07 14:37:51.0        </cas:UPDATETIME>                                    <cas:STATUS>0        </cas:STATUS>                                    <cas:CREATETIME>2016-03-20 18:40:39.0        </cas:CREATETIME>                                    <cas:EMAIL>1        </cas:EMAIL>                                    </cas:attributes>                    </cas:authenticationSuccess></cas:serviceResponse>");

        String text = XmlDealer.getSessionIdFromLogout("<samlp:LogoutRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" ID=\"LR-7-jtRP2XGcFb2PIFZvEMtE7enRAxOXshxRshW\" Version=\"2.0\" IssueInstant=\"2016-04-21T19:31:15Z\"><saml:NameID xmlns:saml=\"urn:oasis:names:tc:SAML:2.0:assertion\">@NOT_USED@</saml:NameID><samlp:SessionIndex>ST-7-3kqtNjRVpSaS4bW6SQ2k-cn.edu.tju.cas</samlp:SessionIndex></samlp:LogoutRequest>");


    }

//    <cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
//    <cas:authenticationSuccess>
//    <cas:user>1</cas:user>
//    <cas:attributes>
//    <cas:CREDIT>1        </cas:CREDIT>
//    <cas:UPDATETIME>2016-04-07 14:37:51.0        </cas:UPDATETIME>
//    <cas:STATUS>0        </cas:STATUS>
//    <cas:CREATETIME>2016-03-20 18:40:39.0        </cas:CREATETIME>
//    <cas:EMAIL>1        </cas:EMAIL>
//    </cas:attributes>
//    </cas:authenticationSuccess>
//    </cas:serviceResponse>

//    <cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
//    <cas:authenticationFailure code="INVALID_TICKET">
//            未能够识别出目标 'ST-2-Yt0tHsdVF3ScRDapC9Sp-cn.edu.tju.cas'票根
//            </cas:authenticationFailure>
//    </cas:serviceResponse>
    public static UserEntity getFromXml(String fileContent) {
        if (fileContent == null || fileContent.isEmpty()) {
            return null;
        }
        fileContent = fileContent.replace("\n", "");
        UserEntity userEntity = null;
        try {
            DocumentBuilder builder = builderFactory.newDocumentBuilder();

            Document document = builder.parse(new InputSource(new ByteArrayInputStream(fileContent.getBytes("utf-8"))));
            Element rootElement = document.getDocumentElement();
            if (rootElement.getElementsByTagName("cas:authenticationSuccess").getLength() > 0) {
//                Element attrs = (Element) rootElement.getElementsByTagName("cas:attributes").item(0);
                userEntity = new UserEntity();
                userEntity.setCreatetime(Timestamp.valueOf(getTagNameValue(rootElement, "cas:CREATETIME")));
                userEntity.setUpdatetime(Timestamp.valueOf(getTagNameValue(rootElement, "cas:UPDATETIME")));
                userEntity.setUsername(getTagNameValue(rootElement, "cas:user"));
                userEntity.setStatus(Integer.valueOf(getTagNameValue(rootElement, "cas:STATUS")));
                userEntity.setEmail(getTagNameValue(rootElement, "cas:EMAIL"));
                userEntity.setCredit(getTagNameValue(rootElement, "cas:CREDIT"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userEntity;
    }

    /**
     * 获取节点中的第一个相符tag的值
     * @param element
     * @param tagName
     * @return
     */
    public static String getTagNameValue(Element element, String tagName) {
        NodeList nodeList = element.getElementsByTagName(tagName);

        if(nodeList.getLength() == 0){
            return "";
        }
        if(nodeList.item(0).getFirstChild().getNodeValue() == null){
            return "";
        }
        return nodeList.item(0).getFirstChild().getNodeValue().trim();
    }

//    <samlp:LogoutRequest
//    xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
//    xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
//    ID="[RANDOM ID]"
//    Version="2.0"
//    IssueInstant="[CURRENT DATE/TIME]">
//    <saml:NameID>@NOT_USED@</saml:NameID>
//    <samlp:SessionIndex>[SESSION IDENTIFIER]</samlp:SessionIndex>
//    </samlp:LogoutRequest>

    public static String getSessionIdFromLogout(String content){
        if (content == null || content.isEmpty()) {
            return "";
        }
        content = content.replace("\n", " ");
        try {
            DocumentBuilder builder = builderFactory.newDocumentBuilder();

            Document document = builder.parse(new InputSource(new ByteArrayInputStream(content.getBytes("utf-8"))));
            Element rootElement = document.getDocumentElement();

            if (rootElement.getElementsByTagName("samlp:SessionIndex").getLength() > 0) {
                String nodeValue = rootElement.getElementsByTagName("samlp:SessionIndex").item(0).getFirstChild().getNodeValue();
                return nodeValue;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
